import axios from 'axios'
import { message } from 'antd'

axios.defaults.baseURL = '/api'
axios.defaults.withCredentials = true
axios.defaults.timeout = 5000

let count = 0
const toLogin = () => {
    count++
    message.error('很抱歉，登录已过期，请重新登录').then(() => {
        console.warn('请重新登录')
    })
}

axios.interceptors.request.use(config => {
    let token = ''
    const userInfo = localStorage.getItem('userInfo')
    if (userInfo) {
        token = JSON.parse(userInfo).token
    }
    config.headers.Authentication = token
    return config
}, error => {
    return Promise.reject(error)
})
axios.interceptors.response.use(res => {
    if (res.status === 200) {
        const { code, message, data } = res.data
        if (code === 200) {
            return data
        } else {
            message.error(message)
        }
    }
}, error => {
    const errorInfo = error.response
    if (errorInfo.status === 401) {
        if (count === 0) {
            toLogin()
        }
    } else {
        message.error(errorInfo.data.message)
        return Promise.reject(error)
    }
})
export default axios
